package com.koron.css2.baseConfig.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BankMapper;
import com.koron.css2.baseConfig.queryBean.BankQueryBean;
import com.koron.css2.baseConfig.vo.BankVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.SelectBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 银行信息-初始化列表
 *
 * @author 廖大富
 */
public class BankList implements ServerInterface {
    private static Logger logger = LogManager.getLogger(BankList.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

        @SuppressWarnings("rawtypes")
        MessageBean<HashMap> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", HashMap.class);
        try {
            BankMapper mapper = factory.getMapper(BankMapper.class);
            BankQueryBean bean = JsonUtils.objectToPojo(req.getData(), BankQueryBean.class);
            PageHelper.startPage(bean.getPage(), bean.getPageCount());
            List<BankVO> beans = mapper.findBank(bean);
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageInfo", new PageInfo<>(beans));
            // 找出所有上级目录，显示分级导航
            ArrayList<HashMap<String, String>> navList = new ArrayList<>();
            recParent(mapper, bean.getBankNo(), navList);
            map.put("navData", navList);
            info.setCode(Constant.MESSAGE_INT_SUCCESS);
            info.setDescription("success");
            info.setData(map);
        } catch (Exception e) {
            info.setCode(Constant.MESSAGE_DBFAIL);
            info.setDescription("数据库异常");
            logger.error("数据库异常", e);
            factory.close(false);
        }
        return info;
    }

    /**
     * 递归查询节点路径，即从根节点到当前节点路径
     *
     * @param mapper
     * @param code
     * @param navList
     */

    private void recParent(BankMapper mapper, String code, ArrayList<HashMap<String, String>> navList) {
        if (code.length() > 0) {
            SelectBean selb = mapper.findBankByCode(code);
            HashMap<String, String> m = new HashMap<>();
            m.put("code", code);
            m.put("name", selb.getName());
            // 存储id和parentId
            m.put("id", selb.getId());
            m.put("parentId", selb.getParentId());
            navList.add(0, m);
            recParent(mapper, code.substring(0, code.length() - 5), navList);
        }
    }

}
